package com.terra.ns.imp.common.vo.validate

import DATE_FORMAT_10
import DATE_FORMAT_14
import DATE_FORMAT_15
import DATE_FORMAT_16
import DATE_FORMAT_19
import DATE_FORMAT_8
import jakarta.validation.ConstraintValidator
import jakarta.validation.ConstraintValidatorContext
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException

/**
@author qins
@date 2022/05/25
@desc 允许的时间字符串格式校验器
 */
class StringDateFormatValidator: ConstraintValidator<StringLocalDateTimeFormat, Any> {

    private lateinit var format: String
    private var allowNull: Boolean = false
    private val allowFormat = listOf(DATE_FORMAT_19,DATE_FORMAT_16,DATE_FORMAT_15, DATE_FORMAT_14, DATE_FORMAT_8,DATE_FORMAT_10)

    override fun initialize(constraintAnnotation: StringLocalDateTimeFormat) {
        format = constraintAnnotation.format
        allowNull = constraintAnnotation.allowNull
    }

    override fun isValid(value: Any?, context: ConstraintValidatorContext?): Boolean {
        if(value == null) {
            return allowNull
        }
        if(!allowFormat.contains(format)) {
            return false
        }
        if(value is String) {
            return try {
                // 系统统一用LocalDateTime
                if(format == DATE_FORMAT_8 || format == DATE_FORMAT_10) {
                    LocalDateTime.parse("$value 00:00:00", DateTimeFormatter.ofPattern("$format HH:mm:ss"))
                } else {
                    LocalDateTime.parse(value, DateTimeFormatter.ofPattern(format))
                }
                true
            } catch (e: DateTimeParseException) {
                false
            }
        }
        return false

    }

}